# windows: celery -A task worker -l info -P solo -n worker@task
# linux: celery -A task worker -l info -P gevent -n worker@task
import logging

import config
# from app import config_db, config_oss
from celery import Celery
from celery.app.log import TaskFormatter
from celery.signals import after_setup_task_logger
from flask import Flask


def create_flask_app():
    _app = Flask(__name__)
    _app.config.from_object(config)

    # config_db(_app)
    # config_oss(_app)

    return _app


def make_celery(app):
    celery = Celery(app.import_name,
                    backend=app.config['CELERY']['result_backend'],
                    broker=app.config['CELERY']['broker_url'])
    celery.conf.update(app.config['CELERY'])

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery


flask_app = create_flask_app()
celery = make_celery(flask_app)


@after_setup_task_logger.connect
def setup_task_logger(logger, *args, **kwargs):
    formatter = TaskFormatter(
        '[%(asctime)s %(task_name)s:%(lineno)s] %(process)d|%(thread)d - %(levelname)s - %(message)s',
        use_color=False)

    # FileHandler Info
    class InfoFilter(logging.Filter):
        def filter(self, record):
            if logging.INFO <= record.levelno < logging.ERROR:
                return super().filter(record)
            else:
                return False

    info_handler = logging.FileHandler(filename=flask_app.config.get('LOG_TASK_INFO'),
                                       mode='a',
                                       encoding='utf-8')
    info_handler.setLevel(logging.INFO)
    info_filter = InfoFilter()
    info_handler.addFilter(info_filter)
    logger.addHandler(info_handler)

    error_handler = logging.FileHandler(filename=flask_app.config.get('LOG_TASK_ERROR'),
                                        mode='a',
                                        encoding='utf-8')
    error_handler.setLevel(logging.ERROR)
    logger.addHandler(error_handler)

    for handler in logger.handlers:
        handler.setFormatter(formatter)


from task import queue_task
